package com.hydra.auth.service.impl;

import com.hydra.auth.service.ValidateCodeService;
import com.hydra.base.error.BusinessException;
import com.hydra.base.redis.RedisPlugin;
import com.hydra.base.utils.FormatUtil;

import javax.annotation.Resource;

public abstract class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private RedisPlugin redisPlugin;

    /**校验格式*/
    protected abstract void validate(String target);

    /**redis前缀*/
    protected abstract String getPrefix();

    /**保存的redis时效(秒)*/
    protected abstract long getSeconds();

    /**真正的发送方法*/
    protected abstract boolean send(String target, String code);

    /**随机验证码*/
    protected String generateCode(){
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        return ""+num;
    }

    /**
     * 发送验证码
     */
    @Override
    public void sendValidateCode(String target, String tag) {
        //校验格式
        this.validate(target);
        String prefix = getPrefix();
        Object validateCode = redisPlugin.get(prefix + tag + ":" + target);
        String code = FormatUtil.isNullToEmpty(validateCode);
        if(FormatUtil.isEmpty(code)){
            code = this.generateCode();
        }
        boolean result = this.send(target, code);
        if(!result){
            return;
        }
        redisPlugin.set(prefix + tag + ":" + target, code, getSeconds());
    }

    /**
     * 校验验证码是否正确
     */
    @Override
    public boolean validate(String target, String tag, String code) {
        //校验格式
        this.validate(target);
        if(FormatUtil.isEmpty(code)){
            throw new BusinessException("验证码不能为空！");
        }
        String prefix = getPrefix();
        Object validateCode = redisPlugin.get(prefix + tag + ":" + target);
        return code.equals(validateCode);
    }
}
